<template>
  <div class="modal">
    <el-dialog v-model="dialogVisible" :title="isNewRef ? '新建角色' : '编辑角色'" width="30%" center>
      <div class="form">
        <el-form :model="formData" label-width="80px" size="large" ref="formRef">
          <el-form-item label="角色id" prop="id">
            <el-input v-model.number="formData.id" placeholder="请输入角色id" :disabled="!isNewRef" />
          </el-form-item>
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="formData.name" placeholder="角色名称" />
          </el-form-item>
          <el-form-item label="角色信息" prop="info">
            <el-input v-model="formData.info" placeholder="角色信息" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmClick">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { storeToRefs } from 'pinia'
import useSystemStore from '@/store/main/system/system'
import { ElForm } from 'element-plus'
// 1. 定义内部的属性
const dialogVisible = ref(false)

const formData = reactive<any>({
  id: 0,
  name: '',
  info: ''
})

const isNewRef = ref(true)
const editData = ref()

const systemStore = useSystemStore()
// 2. 定义设置dialogVisible的方法
function setModalVisible(isNew: boolean = true, itemData?: any) {
  dialogVisible.value = true
  isNewRef.value = isNew
  if (!isNew && itemData) {
    // 编辑数据
    for (const key in formData) {
      formData[key] = itemData[key]
    }
    editData.value = itemData
  } else {
    //新建数据
    for (const key in formData) {
      formData[key] = ''
    }
    editData.value = null
  }
}
// 重置操作 ,绑定form
const formRef = ref<InstanceType<typeof ElForm>>()

// 3. 点击了确定的逻辑
function handleConfirmClick() {
  dialogVisible.value = false
  if (!isNewRef.value && editData.value) {
    //编辑用户数据
    // systemStore.editRoleDataAction(editData.value.id, formData)
    systemStore.editRoleDataAction(formData)
  } else {
    // 创建新的用户
    systemStore.newRoleDataAction(formData)
  }

  //  form中的数据全部重置
  formRef.value?.resetFields()
}

// 暴露的属性和方法
defineExpose({ setModalVisible })
</script>

<style lang="less" scoped>

</style>
